<template>
  <view>
    <scroll-view :style="{ height: `${windowHeight}px`, position: 'relative' }" scroll-y @scrolltoupper="scrollTop" @scrolltolower="scrollBottom" @scroll="handleScroll">
      <view :style="[customStyle]">
        <view v-for="(listSingleItem, pageIndex) in list" :id="`wrp_${pageIndex}`" :key="pageIndex">
          <view v-if="listSingleItem.length > 0">
            <list-item v-for="(listItem, index) in listSingleItem" :key="index" :data="listItem" :index="index">
              <view @click="itemClick(listItem)">
                <slot :data="listItem" :index="index"></slot>
              </view>
            </list-item>
          </view>
          <view v-else :style="`height:${listSingleItem.height}px`" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import ListItem from './list-item'

function throttle(fn, delay) {
  let startTime = new Date()
  return function () {
    const context = this
    const args = arguments
    const endTime = new Date()
    const resTime = endTime - startTime
    // 判断大于等于我们给的时间采取执行函数;
    if (resTime >= delay) {
      fn.apply(context, args)
      // 执行完函数之后重置初始时间，等于最后一次触发的时间
      startTime = endTime
    }
  }
}

export default {
  components: { ListItem },
  props: {
    // 自定义样式，对象形式
    customStyle: {
      type: Object,
      default() {
        return {}
      },
    },
    windowHeight: {
      type: Number,
      default: 300,
    },
  },
  data() {
    return {
      list: [],
      wholePageIndex: 0,
      wholeVideoList: [],
      currentRenderIndex: 0,
      index: 0,
      pageHeightArr: [],
    }
  },
  created() {
    const that = this
  },
  methods: {
    reset() {
      this.list = []
      this.wholePageIndex = 0
      this.wholeVideoList = []
      this.currentRenderIndex = 0
      this.index = 0
      this.pageHeightArr = []
    },
    itemClick(item) {
      this.$emit('itemClick', item)
    },
    scrollTop() {
      this.$emit('top')
    },
    scrollBottom() {
      this.$emit('load')
    },
    handleScroll: throttle(function (e) {
      const realScrollTop = e.detail.scrollTop
      const that = this
      // 滚动的时候需要实时去计算当然应该在哪一屏幕
      let tempScrollTop = 0
      const wholePageIndex = this.wholePageIndex

      for (let i = 0; i < this.pageHeightArr.length; i++) {
        tempScrollTop = tempScrollTop + this.pageHeightArr[i]
        if (tempScrollTop > realScrollTop + this.windowHeight) {
          console.log(`set this.computedCurrentIndex${i}`)
          this.computedCurrentIndex = i
          break
        }
      }
      const currentRenderIndex = this.currentRenderIndex
      if (this.computedCurrentIndex !== currentRenderIndex) {
        // 这里给不渲染的元素占位
        const tempList = new Array(wholePageIndex + 1).fill(0)
        tempList.forEach((item, index) => {
          if (this.computedCurrentIndex - 1 <= index && index <= this.computedCurrentIndex + 1) {
            tempList[index] = that.wholeVideoList[index]
          }
          else {
            tempList[index] = { height: that.pageHeightArr[index] }
          }
        })

        this.currentRenderIndex = this.computedCurrentIndex
        // 渲染第一屏的时候，如果之前这里有看到这里，并且showVideoIcon，那么需要重新绑定一次。
        this.list = tempList
      }
    }, 500),
    setHeight() {
      const that = this
      const wholePageIndex = this.wholePageIndex
      const query = uni.createSelectorQuery().in(this)
      this.$nextTick(() => {
        setTimeout(() => {
          const query = uni.createSelectorQuery().in(this)
          query
            .select(`#wrp_${wholePageIndex}`)
            .boundingClientRect((data) => {
              if (data && data.height) {
                that.pageHeightArr[wholePageIndex] = data.height
              }
            })
            .exec()
        }, 80)
      })
    },
    setListData(arr) {
      console.log(this.wholePageIndex)
      // 第一页数据
      if (this.wholePageIndex == 0) {
        this.$set(this.list, this.wholePageIndex, arr)
        this.setHeight()
        this.wholePageIndex = this.wholePageIndex + 1
        return
      }

      this.wholePageIndex = this.wholePageIndex

      const wholePageIndex = this.wholePageIndex
      this.currentRenderIndex = wholePageIndex
      this.wholeVideoList[wholePageIndex] = arr
      const datas = {}
      const tempList = new Array(wholePageIndex + 1).fill(0)
      if (wholePageIndex > 2) {
        tempList.forEach((item, index) => {
          if (index < tempList.length - 2) {
            tempList[index] = { height: this.pageHeightArr[index] }
          }
          else {
            tempList[index] = this.wholeVideoList[index]
          }
        })
        this.list = tempList
      }
      else {
        this.$set(this.list, this.wholePageIndex, arr)
      }

      this.setHeight()
      this.wholePageIndex = this.wholePageIndex + 1
    },
  },
}
</script>

<style scoped>
.wrp {
  width: 375px;
  height: 200px;
}
</style>
